<template>
  <MyDialog :dialogForm="dialogForm" :dialogVisible="dialogVisible" @listenClose="onClose" @listenConfirm="onSubmit">
    <template #dialogBox>
      <MyForm :formData="formData" @listenClick="listenClick" :isClose="isClose" :isSubmit="isSubmit"
        :isDialogVisible="dialogVisible">
      </MyForm>
    </template>
  </MyDialog>
</template>
<script setup lang='ts'>
import { ref, reactive, watch, getCurrentInstance, computed } from 'vue'
import { ParentForm } from '@/interface/index'
import MyDialog from '@/components/MyDialog.vue'
import { FunTime } from '@/global/methods'
import { ElMessage } from 'element-plus'
import { useStore } from '@/store'
import { useRouter } from 'vue-router'
import { addUserApi, editUserApi, getAreaListApi, userDetailApi } from '@/views/account/api/accountApi'
import { SelectObj } from '@/interface/index'
import { AddUserParams, EditUserParams } from '@/views/account/interface/interface'
const router = useRouter()
const store = useStore()
const { proxy } = getCurrentInstance() as any;

const dialogVisible = ref<boolean>(false)//弹窗是否出现
const isClose = ref<boolean>(false)//弹窗点击关闭 触发表单取消校验提示 
const isSubmit = ref<boolean>(false)//弹窗点击确定 触发表单确定

const dialogForm = {
  width: '30%',
  title: '管理员权限'
}
interface PropsDialog {
  isShowDialog: boolean;//弹窗是否出现
  dialogData?: any
}
const props = withDefaults(defineProps<PropsDialog>(), {
  isShowDialog: false,
});
//封装的表单
const formData = reactive<ParentForm>({
  formItem: [],
  rules: {},
  size: 'large',//'large' | 'default' | 'small'
})
const formData1 = reactive<ParentForm>({
  formItem: [
    { key: 'userName', styleType: 'input', label: '姓名', value: '', placeholder: '请输入姓名' },
    { key: 'userLogin', styleType: 'inputDis', label: '手机号码', value: '', placeholder: '请输入手机号码', type: 'number', disabled: true },
    { key: 'townId', styleType: 'selectDis', label: '所属单位', value: '', disabled: true },
    { key: 'countryId', styleType: 'select', label: '', value: '' },
    { key: 'groupName', styleType: 'input', label: '', value: '', length: '32' },
  ],
  rules: {
    userName: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 2, max: 10, message: '请输入2-10长度用户名', trigger: 'blur' },
    ],
    countryId: [{ required: true, message: '请选择村', trigger: 'change' }],
    groupName: [{ required: true, message: '请填写具体地址', trigger: 'change' }],
  },
  size: 'large',//'large' | 'default' | 'small'
})
const formData2 = reactive<ParentForm>({
  formItem: [
    { key: 'userName', styleType: 'input', label: '姓名', value: '', placeholder: '请输入姓名' },
    { key: 'userLogin', styleType: 'input', label: '手机号码', value: '', placeholder: '请输入手机号码', type: 'number' },
    { key: 'roleId', styleType: 'radio', label: '角色', value: '', placeholder: '请选择', data: [{ label: '管理员', value: 2 }, { label: '督察员', value: 3 }] },
    { key: 'roleAuth', styleType: 'select', label: '督察的乡镇', value: [], placeholder: '请选择', data: [], type: 'multiple', hide(row: any): boolean { return row.roleId == 3 }, },
    {
      key: 'funcAuth', styleType: 'checkbox', label: '功能权限', value: [], placeholder: '请选择',
      data: [
        { label: '账号管理权限', value: '1' },
        { label: '常驻人员数据查询权限', value: '2' },
        { label: '来返人员数据统计权限', value: '3' },
        { label: '数据统计权限', value: '4' },
        { label: '隐患管理权限', value: '5' }
      ]
    },
  ],
  rules: {
    userName: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 2, max: 10, message: '请输入2-10长度用户名', trigger: 'blur' },
    ],
    userLogin: [
      { required: true, message: '请输入手机号码', trigger: 'blur' },
      { min: 11, max: 11, message: '请输入11长度手机号码', trigger: 'blur' },
    ],
    roleId: [{ required: true, message: '请选择角色', trigger: 'change' }],
    roleAuth: [{ required: true, message: '请选择需要督察的乡镇', trigger: 'change' }],
    funcAuth: [{ required: true, message: '请选择功能权限', trigger: 'change' }],
  },
  size: 'large',//'large' | 'default' | 'small'
})
//监控弹窗是否出现
watch(
  () => props.isShowDialog,
  () => {
    onAreaList()//获取所有乡镇
    if (props.dialogData?.userId) {
      //编辑
      dialogForm.title = '编辑'
      formData.formItem = formData1.formItem
      formData.rules = formData1.rules
      onUserDetail()
    } else {
      dialogForm.title = '新增'
      formData.formItem = formData2.formItem
      formData.rules = formData2.rules
      dialogVisible.value = !dialogVisible.value
      formData.formItem.forEach(t => {
        if (t.styleType === 'checkbox' || t.styleType === 'uploads') {
          t.value = []
        } else if (t.styleType === 'switch') {
          t.value = false
        } else {
          t.value = ''
        }
      })
    }
  }
)
//弹窗关闭事件
const onClose = () => {
  isClose.value = !isClose.value
  // props.dialogData.administratorFlag=0
}
//弹窗确定事件
const onSubmit = () => {
  isSubmit.value = !isSubmit.value
}
//表单取消校验 关闭弹窗
const listenMyClose = () => {
  dialogVisible.value = !dialogVisible.value
}
//表单确定  调接口
const listenMySubmit = (formData: any) => {
  let obj = JSON.stringify(formData)
  let val = JSON.parse(obj)
  if (!props.dialogData?.userId) {
    val.roleAuth = val.roleId == 3 ? val.roleAuth.join(',') : ''
    val.funcAuth = val.funcAuth.join(',')
  }
  let params = val
  console.log(params);
  if (props.dialogData?.userId) {
    //编辑
    params.userId = props.dialogData.userId
    onEdit(params)
  } else {
    onAdd(params)
  }
}
//定义方法对象 注意定义的方法 必须在上面已经申明 所以建议objFun申明和 listenClick方法 写在页面最下面
const objFun = { 'listenMyClose': listenMyClose, 'listenMySubmit': listenMySubmit }
// 监听子级表格  传过来的方法
const listenClick = (name: string, val: any) => {
  objFun[name](val)
}
//获取所有乡镇 
const onAreaList = async () => {
  try {
    let params = { id: '0' }
    let res = await getAreaListApi(params)
    if (res?.code === 0) {
      let arr: SelectObj[] = []
      res.data.forEach(t => {
        arr.push({ label: t.name, value: t.areaCode })
      })
      if (props.dialogData?.userId) {
        formData.formItem[2].data = arr
      }
    }
    store.commit('loading/setLoad', false)
  } catch {
    store.commit('loading/setLoad', false)
  }
}
//获取所有乡村
const onCountryList = async (val: any) => {
  try {
    let params = { id: val }
    let res = await getAreaListApi(params)
    if (res?.code === 0) {
      let arr: SelectObj[] = []
      res.data.forEach(t => {
        arr.push({ label: t.name, value: t.areaCode })
      })
      formData.formItem[3].data = arr
    }
    store.commit('loading/setLoad', false)
  } catch {
    store.commit('loading/setLoad', false)
  }
}
//查详情 用户信息
const onUserDetail = async () => {
  try {
    let params = { id: props.dialogData.userId }
    let res = await userDetailApi(params)
    if (res?.code === 0) {
      formData.formItem.forEach(t => {
        let formObj = res.data
        t.value = formObj[t.key] ? formObj[t.key] : ''
        onCountryList(formObj['townId'])
      })
      dialogVisible.value = !dialogVisible.value
    }
    store.commit('loading/setLoad', false)
  } catch {
    store.commit('loading/setLoad', false)
  }
}

//新增提交接口any 写成对应的接口
const onAdd = async (params: AddUserParams) => {
  try {
    let res = await addUserApi(params)
    if (res?.code === 0) {
      dialogVisible.value = !dialogVisible.value
      ElMessage({ type: 'success', message: '新增成功' })
      store.commit('refresh/setRefresh', !store.getters['refresh/getRefresh'])
    }
    store.commit('loading/setLoad', false)
  } catch {
    store.commit('loading/setLoad', false)
  }
}
//编辑提交接口any 写成对应的接口
const onEdit = async (params: EditUserParams) => {
  try {
    console.log(params);
    let res = await editUserApi(params)
    if (res?.code === 0) {
      dialogVisible.value = !dialogVisible.value
      ElMessage({ type: 'success', message: '编辑成功' })
      store.commit('refresh/setRefresh', !store.getters['refresh/getRefresh'])
    }
    store.commit('loading/setLoad', false)
  } catch {
    store.commit('loading/setLoad', false)
  }
}
</script>
<style scoped lang='scss'>

</style>